﻿{% extends 'base.html' %}


{% block title %}
Artifical Intelligence Assistant(AIA) Chats
{% endblock %}

{% block headblock %}
<h2>Chat with AIA(Artifical Intelligence Assistant)</h2>
{% endblock %}

{% block contents %}
    <!--
    background-image: url(/media/images/operation/up_bg.png); 
    -->
    <div style="text-align: center;">
        <img id="previousChatsButton" src="/media/images/operation/up.png" style="width:56px; height:27px;"/>
        <span id='previous_load' style='display:none;align:center;vertical-align:middle;text-align:center;'>
            <img src='/media/images/ajax-loader.gif' style="width:27px; height:27px;"/>
        </span>
    </div>
    <input id="currentclskey" name="currentclskey" type="hidden" value="None" />
    <input id="firstmsgkey" name="firstmsgkey" type="hidden" value="" />
    <input id="lastmsgkey" name="lastmsgkey" type="hidden" value="" />

    <div id="contents" class="body" style="height: 460px; overflow-y: scroll;">
    {% include "chat_items.html" %}
    </div>
    <strong>Tip: 双击聊天内容区可修改更新，单击标题可更改类别。</strong><br/><br/>
    
    
    {% ifequal url_linktext 'Login' %}
    <strong>Please <a href="{{ url }}"><strong>{{ url_linktext }}</strong></a> to chat with your own private assistant!</strong>
    {% endifequal %}

    {% ifnotequal url_linktext 'Login' %}
    <!--
    <image src="/media/images/icon/icon14.jpg" width="20" height="20"/>
    -->
    <strong>Hi <font color="blue">{{ user.nickname }}</font>, I am your personal assistant. Can I help you?<strong>
    {% endifnotequal %}
    
    <div class="chattextarea">
    <form>
        <textarea style="height:100px; width:100%" name="message" id="message" rows="4"></textarea>
    </form>
    <strong>
        Tip: Press <font color="red">Enter</font> to submit, <font color="blue">SHIFT+ENTER</font> to make a new line. Just like Google Talk.<br/>
    </strong>
    </div>

{% endblock %}



{% block login %}
    <a href="{{ url }}">{{ url_linktext }}</a>
{% endblock %}


{% block userdefinedblock %}

    <div class="body">
        <h3>Classification</h3>
        <div id="classmenulist">
        
            <span class="classmenuitem">
                <span class="classicon" style="background-color: LightGray;">
                    <span class="classname">
                    ALL
                    </span>
                </span>
                <input id="clskey" type="hidden" value="None"/>
            </span>

            <div id="classlist">
                <span class="classmenuitem">
                    <span class="classicon" style="background-color: blue;">
                        <span class="classname">
                        None
                        </span>
                    </span>
                    <input id="clskey" type="hidden" value="notmarked"/>
                </span>
                {% for cls in clss %}
                {% include "class_item.html" %}
                {% endfor %}
            </div>
        </div>
        
        {% ifequal admin 'admin' %}
            <form>
                name:<input id="addclassname" name="name" type="text" value="" /><br/>
                color:<input id="addclassiconcolor" name="iconcolor" type="text" value="#fffa7a" /><br/>
                <input id="addclassbutton" type="button" title="ADD" value="ADD" />
            </form>
        {% endifequal %}
    </div>
    
    {% ifequal admin 'admin' %}
    <div class="body">
        <h3>Users of AIA</h3>
        {% for usr in usrs %}
        {{ usr.user.nickname }} {{ usr.access_count }}
        <span>
        <span class="localdatetime">{{ usr.last_update|date:"Y-m-d H:i:s" }}</span>
        <input class="localdatetimevalue" type="hidden" value='{{ usr.last_update|date:"Y,m,d,H,i,s" }}' />
        </span>
        <br/>
        {% endfor %}
    </div>
    {% endifequal %}
    
    
    <div class="body">
        <h3>AIA Bots</h3>
        <strong>Gtalk</strong>: <font color="blue">aiassistantbot@gmail.com</font> (<span id="botstatus"></span>)<br/>
        <script type="text/javascript">
        function checkBotStatus(){
            $.post("/chat/botstatus/",
                {url : "http://www.google.com/talk/service/badge/Show?tk=z01q6amlq9tj4m12hqf82nf1ibici0h61b7tqk5pi39ceob0qkc3qokkdtq0bsndc7utcsctnitidu77gd7lt880hmgit0l0jure5nojfq8occ7opskk7kbjqfoatfo7kvej9ntnc429jtorq3tcdscfr73f23qbfq6751fa8qkj5mqjtrhq4p8ch0bai8a6o1u8qskuipi5jl61qjju68aot53q0&amp;w=200&amp;h=60"}, 
                //{http://www.google.com/talk/service/badge/Show?tk=z01q6amlqq4frp2m8pg4oncftbrmpfl3255n78pb9li4ku0nun8u30k514pmlsi23dbbup7rar4nt8rhk3ag3vi1ofi2b4ud6hnn3a3g5uerf9d5iquf2hqotnjd62bjut8r95aigcst3d4g&amp;w=200&amp;h=60"}, 
                function(data){
                    //alert("Data Loaded: " + data);
                    if(data=="Available"){
                        $("#botstatus").css("color","green");
                    }else if(data=="Busy"){
                        $("#botstatus").css("color","red");
                    }else{
                        $("#botstatus").css("color","gray");
                    }
                    $("#botstatus").html(data);
                }
            );
            $("#botstatus").html("<img src='/media/images/ajax-loader1.gif'  style='width:12px;height:12px' />");
        }
        
        $(document).ready(function() {
            checkBotStatus();
        });
        
        $("#botstatus").everyTime('50s', 'checkBotStatus', checkBotStatus, 0, true);
        
        $("#botstatus").click(function(event){
            checkBotStatus();
        });
        
        </script>
    </div>
    
    <div class="body">
        <h3>Source Code</h3>
        <a href="/media/realeases/AIAssistant-0.0.2.zip">AIAssistant-0.0.2.zip</a>
    </div>
    <!--
    <div class="body">
        <h3>Sites</h3>
        <a href="http://code.google.com/p/aiassistant" target="_blank">AIAssistant(Google Code)</a><br/>
        <a href="http://groups.google.com/group/aiassistantbbs" target="_blank">AIAssistant(Google Group)</a><br/>
        <a href="http://code.google.com/appengine/" target="_blank">App Engine</a><br/>
        <a href="http://code.google.com/appengine/docs/" target="_blank">App Engine Doc</a><br/>
        <a href="http://groups.google.com/group/google-appengine/topics" target="_blank">App Engine Group</a><br/>
    </div>
    
    <div class="body">
        <h3>Others</h3>
        <a href="http://code.google.com/p/pygtalkrobot" target="_blank">PygtalkRobot(Google Code)</a><br/>
        <a href="http://groups.google.com/group/pygtalkrobot" target="_blank">PygtalkRobot(Google Group)</a><br/>
        <a href="http://newsmth.appspot.com/" target="_blank">SouSMTH</a><br/>
        <a href="http://newsmth.appspot.com/" target="_blank">SouSMTH Bot: smth.bot@gmail.com</a><br/>
        <a href="http://code.google.com/p/newsmth" target="_blank">SouSMTH(Google Code)</a><br/>
        <a href="http://groups.google.com/group/newsmthbbs" target="_blank">SouSMTH(Google Group)</a><br/>
        <a href="http://www.google.com/analytics/" target="_blank">Google Analytics</a><br/>
    </div>
    -->
    
{% endblock %}



{% block script %}

    <style type="text/css" media="all">
        @import url( /media/scripts/ColorPicker/ColorPicker.css );
    </style>
    
    <script src="/media/scripts/ColorPicker/ColorPicker.js" type="text/javascript"></script>
    <script src="/media/scripts/rgbcolor.js" type="text/javascript"></script>
    
    <script src="/media/scripts/jquery.dump.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        
        function scrollContentsToBottom(){
            var scrollHeight = document.getElementById("contents").scrollHeight;
            document.getElementById("contents").scrollTop = scrollHeight;
            
            //alert($("#contents").height()+","+$("#contents").innerHeight()+","+$("#contents").outerHeight())
            //$("#contents").scrollTop($("#contents").outerHeight());
        }
        
        function scrollContentsToTop(){
            //document.getElementById("contents").scrollTop = 0;
            
            $("#contents").scrollTop(0);
        }
        
        function changeColors(){
            
            $(".chattitle").each(function(i){
                title_bgcolor = $(this).css("background-color");
                $(this).siblings(".chatcontent").css("border-color", title_bgcolor);
                var title_color = new RGBColor(title_bgcolor);
                if(title_color.ok){
                    //alert(title_color.toContrastHex());
                    $(this).find(".chatauthor").css("color", title_color.toContrastHex());
                }
            });
            
            $(".classmenuitem").each(function(i){
                title_bgcolor = $(this).find(".classicon").css("background-color");
                var title_color = new RGBColor(title_bgcolor);
                if(title_color.ok){
                    //alert(title_color.toContrastHex());
                    $(this).find(".classname").css("color", title_color.toContrastHex());
                }
            });
            
        }
        
        function addClassMenuEvent(classmenuitems){
            var classmenus =  $("#classlist .classmenuitem").clone();
            classmenus.unbind();
            //classmenus.attr("id", "justchangeit");
            
            classmenus.click( function(event){
                var msg_key = classmenuitems.siblings("#msgkey").val();
                
                var old_cls_key = $("#title_"+msg_key).find("#msgclskey").val();
                if(old_cls_key == ""){
                    old_cls_key = "notmarked";
                }
                var cls_key = $(this).find("#clskey").val();
                
                if(old_cls_key != cls_key) {
                    //alert("msgkey:"+ msg_key+", clskey:"+cls_key+", oldclskey:"+old_cls_key);
                    $.post( "/chat/mark/", { msgkey: msg_key, clskey: cls_key, email: "anonymous@gmail.com" },
                        function(data){
                            if(data.indexOf("error!")==0) {
                                var errorMsgIndex = data.indexOf("!")+1;
                                var errorMsg = data.substring(errorMsgIndex);
                                alert(errorMsg);
                            } else {
                                //alert(data);
                                var datas = data.split(",");
                                var msgkey = datas[0];
                                var clskey = datas[1];
                                var titlecolor = datas[2];
                                var cls_name = datas[3];
                                //alert(cls_name);
                                
                                $("#title_"+msgkey).find("#msgclskey").val(clskey);
                                
                                $("#title_"+msgkey).find(".chatauthor:last").html("["+cls_name+"]");
                                
                                $("#title_"+msgkey).css("background-color", titlecolor);
                                $("#title_"+msgkey).siblings(".chatcontent").css("border-color", titlecolor);
                                //alert(titlecolor);
                                var title_color = new RGBColor(titlecolor);
                                if(title_color.ok){
                                    //alert(title_color.toContrastHex());
                                    $("#title_"+msgkey).find(".chatauthor").css("color", title_color.toContrastHex());
                                }
                                
                                currentClskey = $("#currentclskey").val();
                                if( currentClskey!="None" && currentClskey!=clskey ){
                                    //alert(currentClskey);
                                    $("#title_"+msgkey).parent().remove();
                                }
                            }
                        }
                    );
                    $("#title_"+msg_key).find(".chatauthor:last").html("[<img src='/media/images/ajax-loader2.gif'></img>]");
                }
                
                $("#title_"+msg_key).siblings(".classmenu").css("display", "none");
                $("#title_"+msg_key).find(".menuitemarrow").html("&#9658;");
            });

            classmenuitems.empty();
            classmenuitems.append(classmenus);
        }
        
        function addChatContentEvent(){
            $(".chatcontent").dblclick( function (event){
                var msg = $(this).html();
                //alert(msg)
                //$("#message").val(msg);
                msg = msg.replace(/<span.*?>/gi, "");
                msg = msg.replace(/<\/span>/gi, "");
                msg = msg.replace(/ /gi, "");
                msg = msg.replace(/\n/gi, "");
                msg = msg.replace(/<br\/>/gi, "\n");
                msg = msg.replace(/<br>/gi, "\n");
                msg = msg.replace(/&amp;/gi, "&");
                msg = msg.replace(/&gt;/gi, ">");
                msg = msg.replace(/&lt;/gi, "<");
                msg = msg.replace(/&nbsp;/gi, " ");
                //$("#message").val($("#message").val()+"\n------\n"+msg);
                
                var html = "<textarea class='chatedittextarea'>"+msg+"</textarea>";
                var edittextarea = $(html);
                edittextarea.css("height", $(this).height());
                
                $(this).empty();
                $(this).append(edittextarea);
                edittextarea.focus();
                
                $(this).unbind();
                addEditEvent(edittextarea);
            });
            
            //$(".chatcontent").mouseover( function (event){});
        }
        
        function chatEditEventFunction(event){
            if( event.type == "blur" || (event.type="keypress" &&event.keyCode == 13 && !event.shiftKey)){
                //$(this).attr("disabled", "true");
                var msg = $(this).val();
                var msgkey = $(this).parent().siblings(".classmenu").find("#msgkey").val();
                $(this).parent().attr("id", "textarea_"+msgkey);
                
                //alert(msgkey+", "+msg);
                //$("#message").val(msgkey+","+msg);
                $.post( "/chat/edit/",
                    { msgkey: msgkey, message: msg, email: "anonymous@gmail.com" },
                    function(data){
                        if(data!=""){
                            if(data.indexOf("error!")==0) {
                                var errorMsgIndex = data.indexOf("!")+1;
                                var errorMsg = data.substring(errorMsgIndex);
                                alert(errorMsg);
                            } else {
                                //alert(data);
                                //$("#message").val($("#message").val()+"\ndata:"+data);
                                var commaindex = data.indexOf(",");
                                //alert(commaindex);
                                var msgkey = data.substring(0, commaindex);
                                //alert(msgkey);
                                var msg = data.substring(commaindex+1);
                                //alert(msg);
                                $("#textarea_"+msgkey).html(msg);
                            }
                        }
                    }
                );
                //$("#message").val(msg);
                msg = msg.replace(/&/g, "&amp;")
                msg = msg.replace(/>/g, "&gt;")
                msg = msg.replace(/</g, "&lt;")
                msg = msg.replace(/\n/g, "<br/>")
                msg = msg.replace(/ /g, "&nbsp;")
                //alert(msg)
                //$("#message").val($("#message").val()+"\n\n"+msg);
                
                $(this).parent().html(msg);
                
                addChatContentEvent();
                
            }
        }
        
        function addEditEvent(edittextarea){
            //edittextarea = edittextarea.find(".chatedittextarea");
            edittextarea.unbind();
            edittextarea.blur(chatEditEventFunction);
            edittextarea.keypress(chatEditEventFunction);
        }
        
        function addChatEvent(){
            //alert("aaaaaaa");
            $(".chattitlemenu").unbind();
            $(".chattitlemenu").click( function(event){
                //alert("xxxxxx");
                var classmenu = $(this).parent().siblings(".classmenu");
                var classmenuitems = classmenu.find("#classmenuitems");
                
                //var display = classmenu.css("display")=="none"? "block":"none";
                //classmenu.css("display", display);
                
                classmenu.toggle();
                
                if(classmenu.css("display") == "block"){
                    addClassMenuEvent(classmenuitems);
                    $(this).find(".menuitemarrow").html("&#9660;");
                }else{
                    classmenuitems.empty();
                    $(this).find(".menuitemarrow").html("&#9658;");
                }
            });
            //alert("bbbb");
            addChatContentEvent();
            //alert("ccccc");
        }

        function updateFirstAndLastMsgKey(){
            var lastmsgkey = $(".classmenu:last #msgkey");
            if(lastmsgkey.val()) {
                $("#lastmsgkey").val(lastmsgkey.val());
            } else {
                $("#lastmsgkey").val("None");
            }
            //alert("aaa");
            //$("#message").val("lastmsgkey: "+$("#lastmsgkey").val());
            
            
            var firstmsgkey = $(".classmenu:first #msgkey");
            if(firstmsgkey.val()) {
                $("#firstmsgkey").val(firstmsgkey.val());
            } else {
                $("#firstmsgkey").val("None");
            }
            //$("#message").val("firstmsgkey: "+$("#firstmsgkey").val());
            
        }

        function startAutoUpdate(){
            
            var updateChatsFunction = function() {
                //$("#message").val($("#message").val()+"\nmsgkey 1:"+$("#lastmsgkey").val());
                
                $.post( "/chat/update/",
                    { msgkey: $("#lastmsgkey").val(), clskey: $("#currentclskey").val(), email: "anonymous@gmail.com" },
                    function(data){
                        if(data!=""){
                            //alert(data);
                            //$("#message").val($("#message").val()+"\ndata:"+data);
                            $("#contents").append($(data));
                            toLocalDateTime();
                            scrollContentsToBottom();
                            addChatEvent();
                            updateFirstAndLastMsgKey();
                        }
                        
                        startAutoUpdate();
                    }
                );
                
                /*
                $.post("/chat/json/", { data: "John" }, 
                    function(json){
                        //alert("JSON Data:" + data);
                        //$.dump(json);
                        //$("#message").val(json[1].bar[0]);
                        
                    }, 
                    "json"
                );
                */
                
            };
            
            $("#contents").oneTime('30s', 'chatupdate', updateChatsFunction, 0, true);
        }
        
        function stopAutoUpdate(){
            $("#contents").stopTime('chatupdate');
        }
        
        
        function getLocalDate(dtString){
            var dts = dtString.split(",");
            y = dts[0];
            M = dts[1];
            d = dts[2];
            h = dts[3];
            m = dts[4];
            s = dts[5];
            
            var time = Date.UTC(y, M-1, d, h, m, s);
            var date = new Date();
            date.setTime(time);
            return date.toLocaleString();
            //alert(date.toLocaleString());
        }
               
        function toLocalDateTime(){
            /*
            $(".localdatetime").each(function(i){
                var localdatetimevalue = $(this).siblings(".localdatetimevalue").val();
                //getLocalDate(localdatetimevalue);
                $(this).html("["+getLocalDate(localdatetimevalue)+"]")
            });
            */
        }
        
        function init(){
            toLocalDateTime();
            scrollContentsToBottom();
            $("#message").focus();
            addChatEvent();
            updateFirstAndLastMsgKey();
            changeColors();
            $("#addclassiconcolor").attachColorPicker();
            startAutoUpdate();
        }
    </script>
    
    <script type="text/javascript">
        $(document).ready(function() {
            
            init();
            
            $("#message").keypress( function(event){
                if(event.keyCode == 13 && !event.shiftKey){
                    
                    stopAutoUpdate();
                    
                    $("#message").attr("disabled", "true");
                    //alert(encodeURIComponent($(this).val()));
                    $.post( "/chat/add/",
                        { message: $(this).val(), email: "anonymous@gmail.com" },
                        function(data){
                            $("#contents").append($(data));
                            $("#message").val("");
                            $("#message").removeAttr("disabled");
                            $("#message").focus();
                            
                            scrollContentsToBottom();
                            addChatEvent();
                            updateFirstAndLastMsgKey();
                            
                            startAutoUpdate();
                        }
                    );
                }
            });
            

            $("#addclassbutton").click( function(event){
                $.post( "/chat/addclass/",
                    { name: $("#addclassname").val(), iconcolor: $("#addclassiconcolor").val(), email: "anonymous@gmail.com" },
                    function(data){
                        if(data.indexOf("error!")==0) {
                            var errorMsgIndex = data.indexOf("!")+1;
                            var errorMsg = data.substring(errorMsgIndex);
                            alert(errorMsg);
                        } else {
                            //alert(data)
                            //alert($("#classlist").html());
                            $("#classlist").append($(data));
                        }
                    }
                );
            });
            
            $("#classmenulist .classmenuitem").click( function(event){
                clskey_value = $(this).find("#clskey").val();
                $("#currentclskey").val(clskey_value);
                $.post( "/chat/update/",
                    { msgkey : "None", clskey : clskey_value, email: "anonymous@gmail.com" },
                    function(data){
                        //alert(data);
                        //$("#message").val($("#message").val()+"\ndata:"+data);
                        $("#contents").empty();
                        $("#contents").append(data);
                        changeColors();
                        toLocalDateTime();
                        scrollContentsToBottom();
                        addChatEvent();
                        updateFirstAndLastMsgKey();
                    }
                );
                $("#contents").empty();
                $("#contents").html("<div style='height:100%;align:center;vertical-align:middle;text-align:center;'><img src='/media/images/ajax-loader.gif' /></div>");
            });
            
            var previousChatsEventFunction = function(event){
                //alert($("#firstmsgkey").val());
                clskey_value = $("#currentclskey").val();
                //alert(clskey_value);
                scrollContentsToTop();
                $.post( "/chat/previous/",
                    { msgkey : $("#firstmsgkey").val(), clskey : clskey_value, email: "anonymous@gmail.com" },
                    function(data){
                        if(data!=""){
                            //alert(data);
                            //$("#message").val($("#message").val()+"\ndata:"+data);
                            $("#contents").prepend(data);
                            changeColors();
                            toLocalDateTime();
                            scrollContentsToTop();
                            addChatEvent();
                            updateFirstAndLastMsgKey();
                        } else {
                            //alert("No more previous chats.");
                        }
                        $("#previous_load").css("display", "none");
                        $('#previousChatsButton').css("display", "inline");
                    }
                );
                $("#previous_load").css("display", "inline");
                $('#previousChatsButton').css("display", "none");
            };
            
            $('#previousChatsButton').click( previousChatsEventFunction );
            
            $("#contents").scroll(function(event){
                if( event.type == "scroll"){
                    var scrollHeight = document.getElementById("contents").scrollHeight;
                    if($("#contents").scrollTop()==0){
                        //$("#message").val($("#contents").scrollTop()+","+scrollHeight);
                        //alert($("#contents").height());
                        //alert($("#contents").scrollTop());
                        //previousChatsEventFunction(event);
                        
                    } else if ( ($("#contents").scrollTop()+$("#contents").innerHeight()) == scrollHeight ){
                        //$("#message").val("X:"+$("#contents").scrollTop()+","+$("#contents").innerHeight()+","+scrollHeight);
                        //updateChatsFunction();
                    }
                }
            });
            
            
        });
    </script>
    
    <script type="text/javascript">
        
    </script>
{% endblock %}

